home *** CD-ROM | disk | FTP | other *** search
/ 500 MB Nyheder Direkte fra Internet 2 / 500 MB nyheder direkte fra internet CD 2.iso / start / data / text / c.txt < prev    next >
Text File  |  1994-09-21  |  43KB  |  942 lines

  1.  
  2.                  FUN
  3.   C is a computer language invented by Dennis Ritchie in 1972, 
  4. while he was working for AT&T at Bell Labs. He called it ``C'' 
  5. because it came after ``B'', which was an earlier language 
  6. developed by a colleague.
  7.   Earlier chapters of The Secret Guide to Computers explained how 
  8. to program in BASIC and PASCAL. C resembles those languages but 
  9. has two advantages: C runs faster and consumes less RAM.
  10.   C has become the most popular language for creating advanced 
  11. programs. The world's largest software companies have switched to 
  12. C from assembly language:
  13. Created using assembly lang.Created using C
  14. DBASE 2             DBASE 3, 3+, 4, and 5
  15. Word Perfect 4.0, 4.1, and 4.2Word Perfect 5, 5.1, and 6
  16. 1-2-3 release 1, 1A, 2, 2.01, 2.2, 2.3, 2.41-2-3 release 3, 3.1, 
  17. 3.2, 3.3, 3.4
  18.   If you become an expert C programmer, you can help run those 
  19. rich software companies and get rich yourself!
  20.   Before studying C, study BASIC and PASCAL, which are similar 
  21. but easier.
  22.   Unlike BASIC and PASCAL, C lets you easily create a pointer, 
  23. which is a note about which part of RAM to use. If you create the 
  24. pointer incorrectly, C will use the wrong part of RAM ___ and 
  25. erase whatever information had been there before. For example, C 
  26. might erase the part of RAM used by DOS, so that DOS becomes 
  27. confused and accidentally erases your disks!
  28.   A faulty pointer (which points to the wrong part of RAM) is 
  29. called a runaway pointer, and it's a C programmer's greatest 
  30. fear. Even if your innocent-looking program doesn't seem to 
  31. mention pointers, a small error in your program might make C 
  32. create a pointer that wrecks your computer. That's why many C 
  33. programmers look thin and haggard and bite their nails. To keep 
  34. your nails looking pretty, make backup copies of your floppy and 
  35. hard disks before trying to program in C.
  36.   C is like a sports car with no brakes: it's fast, fun, slim, 
  37. sleek, and dangerous. If you program in C, your friends will 
  38. admire you and even whistle at you as you zoom along the freeway 
  39. of computer heaven; but if you're not careful, your programs and 
  40. disks will crash, and so will your career!
  41.                                                    Versions of C
  42.                                          For the IBM PC, the 
  43. nicest kinds of C are Quick C and Turbo C.
  44.                                          Quick C, published by 
  45. Microsoft, lists for $99. You can buy it from discount dealers 
  46. for just $59. Another way to get Quick C is to buy a combination 
  47. package called Quick C with Quick Assembler. Discount dealers 
  48. sell that combo for $139. Another combo is called the Microsoft C 
  49. package: it contains Quick C and also an optimizing version of C 
  50. (which produces programs that run faster). Discount dealers sell 
  51. it for $293.
  52.                                          Turbo C is published by 
  53. Borland. Although it's slightly harder to use than Quick C, many 
  54. programmers prefer it because it runs much faster, consumes less 
  55. RAM and disk space, comes with better instruction manuals, 
  56. handles advanced topics more simply, and can be copied more 
  57. easily onto your hard disk.
  58.                                          C++ You can buy a 
  59. variant of C called C++. It's harder to learn than C. It lets you 
  60. use an advanced technique called object-oriented programming 
  61. (OOP), in which you define ``objects'' and give those objects 
  62. ``properties''.
  63.                                          To explore C++, get 
  64. Microsoft's Visual C++ for Windows ($75) or Borland's Turbo C++ 
  65. ($67 for the DOS version, $74 for the Windows version). Those are 
  66. the prices charged by discount dealers such as Computer Discount 
  67. Warehouse (800-454-4CDW).
  68.                                          When you buy Turbo C++, 
  69. you get a free copy of Turbo C, so you get both languages for a 
  70. low total price!
  71.                                          Mac The best version of 
  72. C for the Mac is Think C. It's published by the Lightspeed 
  73. division of Symantec. You can get it for $165 from discount 
  74. dealers such as Mac Connection.
  75.                                          Where to begin Since C++ 
  76. is harder than C, begin by learning C. Here's how to use Quick C 
  77. (version 2) and Turbo C (version 2).
  78.  
  79.                                                Copy to the hard disk
  80.                                          Turbo C and Quick C come 
  81. on floppy disks, which you should copy to your hard disk. Here's 
  82. how.
  83.                                          Turn on the computer 
  84. without any floppy in drive A. As I explained in the MS-DOS 
  85. chapter, make sure your hard disk contains a CONFIG.SYS file 
  86. saying ``files=20'' (or a bigger number) and ``buffers=10'' (or a 
  87. bigger number).
  88.                                          Here's what to do next.
  89.                                          Turbo C Turbo C comes on 
  90. six 5¼-inch floppy disks. When you see the C prompt, put the 
  91. Turbo C Install/Help Disk in drive A and type ``a:''. The 
  92. computer displays an A prompt.
  93.                                          Type ``install''. The 
  94. computer says ``Turbo C Installation Utility''.
  95.                                          Press ENTER three times. 
  96. The computer says ``Turbo C Directory''. Press the F9 key.
  97.                                          When the computer tells 
  98. you, put the other Turbo C disks in drive A and press ENTER.
  99.                                          The computer says 
  100. ``Turbo C is now installed on your system.'' Ignore the 
  101. computer's comments about PATH. Press ENTER.
  102.   Turn off the computer, so you can start fresh.
  103.   Quick C Quick C comes on ten 5¼-inch floppy disks. Put the 
  104. Quick C Setup Disk in drive A and type ``a:''. The computer 
  105. displays an A prompt.
  106.   Type ``setup''. The computer says ``Microsoft Quick C Setup 
  107. Program''. Press ENTER ten times.
  108.   The computer asks, ``Include in combined libraries?'' The 
  109. computer is asking whether you're planning to write programs that 
  110. include graphics. Most C programs do not use graphics; most C 
  111. courses do not discuss graphics; this chapter does not discuss 
  112. graphics. Chapter 12 of the Quick C instruction manual does 
  113. discuss graphics. If you plan to study and use graphics, press Y 
  114. and ENTER, then Y again and ENTER (which makes the computer copy 
  115. graphics commands to the hard disk); otherwise, press ENTER twice 
  116. (so the computer doesn't bother copying graphics commands to the 
  117. hard disk, and your hard disk won't be so full).
  118.   The computer asks, ``Do you want to change any of the above 
  119. options?'' Press N and ENTER.
  120.   The computer asks, ``Install Microsoft Mouse?'' If you have a 
  121. Microsoft Mouse (or clone), press ENTER; if you have no mouse or 
  122. a different brand, press N then ENTER.
  123.   Press ENTER four more times. The computer asks again, ``Do you 
  124. want to change any of the above options?'' Press N and ENTER.
  125.   Press ENTER eight more times. The computer asks again, ``Do you 
  126. want to change any of the above options?'' Press N and ENTER.
  127.   Press ENTER again. When the computer tells you, put other Quick 
  128. C disks in drive A press ENTER.
  129.   The computer says, ``Press any key to start building combined 
  130. libraries.'' Press ENTER twice. Ignore the computer's comments 
  131. about ``creating sample configuration files''.
  132.   You'll see an A prompt. Type ``copy con c:\qc2\qc2.bat'' (and 
  133. press ENTER at the end of that command). Underneath that command, 
  134. type this:
  135. set lib=\qc2\lib
  136. set include=\qc2\include
  137. cd bin
  138. qc
  139. cd \
  140. Underneath all that, press the F6 key then ENTER.
  141.   Turn off the computer, so you can start fresh.
  142.  
  143.                Start C
  144.   To start using C, turn on the computer without any floppy in 
  145. drive A.
  146.   To do Turbo C, type ``do tc''. To do Quick C, type ``do qc2''.
  147.   (That ``do'' method works if you put the DO.BAT file onto your 
  148. hard disk as I recommended in the MS-DOS chapter. If you have not 
  149. put DO.BAT onto your hard disk, do Turbo C by typing ``cd tc'' 
  150. and then ``tc''; do Quick C by typing ``cd qc2'' and then 
  151. ``qc2''.)
  152.   If you're using Turbo C, then press F10.
  153.                                                  Type your program
  154.                                          For example, type this C 
  155. program:
  156. main(){
  157.         puts("make your nose");
  158.         puts("touch your toes");
  159.         }
  160.                                          The program begins by 
  161. saying ``main()'', which means: here comes the main program.
  162.                                          Do not capitalize the 
  163. word ``main''. If you type ``MAIN'' instead of ``main'', the 
  164. computer will gripe. In C, you must type all commands by using 
  165. lower-case letters, not capitals.
  166.                                          After the ``main()'', 
  167. the rest of the program is enclosed in braces: {}. Like PASCAL's 
  168. ``BEGIN'' and ``END'', they mark the beginning and end of the 
  169. program.
  170.                                          The lines between the 
  171. braces are indented. To indent, tap the TAB key. The indentation 
  172. is optional but helps other programmers understand your program.
  173.                                          Once you've indented a 
  174. line, the computer automatically indents all the lines underneath 
  175. it. (If the computer automatically indents a line that you don't 
  176. want to indent, press the BACKSPACE key.)
  177.                                          The indented lines tell 
  178. the computer to print two strings: ``make your nose'' and ``touch 
  179. your toes''.
  180.                                          Notice that C says 
  181. ``puts'' instead of ``print''. (BASIC says PRINT; PASCAL says 
  182. WRITELN; C says ``puts'' instead.) The command ``puts'' means: 
  183. put the string onto your screen.
  184.                                          After ``puts'', you must 
  185. put parentheses. (PASCAL's WRITELN requires parentheses also.)
  186.                                          Like BASIC, C makes you 
  187. put each string in quotation marks.
  188.                                          Like PASCAL, C requires 
  189. a semicolon at the end of each typical line. Here's the rule: 
  190. each line of C should end with a semicolon or brace.
  191.  
  192.                                                   Run the program
  193.                                          When you finish typing 
  194. the program, tell the computer to run it. Here's how: for Turbo 
  195. C, press F10 then type RR; for Quick C, press F5 and if the 
  196. computer asks ``Rebuild?'' press ENTER.
  197.                                          If you typed the program 
  198. wrong, the computer will say ERRORS. (If you're using Turbo C, 
  199. then press ENTER and F6.) Correct the error, then tell the 
  200. computer to run the program again.
  201.                                          When the computer runs 
  202. the program correctly, the computer prints:
  203. make your nose
  204. touch your toes
  205. (If you're using Turbo C, that printing flashes on the screen too 
  206. briefly for you to read; after the flash, press Alt with F5, 
  207. which makes the printing reappear.)
  208.                                          After the computer's run 
  209. the program successfully and you've read what the computer 
  210. printed, press ENTER.
  211.        Manipulate your program
  212.   Here's how to manipulate your program.
  213.   Turbo C Turbo C lets you manipulate your program in the same 
  214. way as Turbo PASCAL 5.5. For details, read the explanation of 
  215. Turbo PASCAL 5.5 on pages 391-392. On those pages, read the 
  216. sections entitled ``Advanced editing'', ``Save your program'', 
  217. ``Switch programs'', and ``Exit''.
  218.   Quick C Quick C lets you manipulate your program in the same 
  219. way as Quick PASCAL. For details, read the explanation of Quick 
  220. PASCAL on pages 385-386. On those pages, read just the sections 
  221. entitled ``Advanced editing'' and ``Save your program''.
  222.   Here's how to do further manipulations in Quick C. . . . 
  223.   Save your program. To copy your program to the hard disk, press 
  224. the Alt key then say ``File Save'' (by typing FS). If the 
  225. computer says ``File Name'', type a name for the program (such as 
  226. NOSE) and press ENTER. If you called the program ``NOSE'', the 
  227. computer will put the program onto the hard disk as ``NOSE.C''. 
  228. (It will be in the BIN subdirectory of the QC2 subdirectory.)
  229.   Erase the screen. To erase the screen so you can start writing 
  230. a new program, press the Alt key then say ``File New'' (by typing 
  231. FN). If the computer asks ``Do you want to save?'', press N.
  232.   Retrieve a program. To retrieve a saved program, press the Alt 
  233. key then say ``File Open'' (by typing FO). Type the program's 
  234. name (such as NOSE) and press ENTER. If the computer asks ``Do 
  235. you want to save?'', press N.
  236.   Exit. When you finish using Quick C, here's how to return to 
  237. the DOS prompt. Press the Alt key. Say ``File eXit'' (by typing 
  238. FX). If the computer asks ``Do you want to save?'', press N.
  239.  
  240.             Many versions
  241.   Suppose you write a program, save it as ``NOSE'', and then run 
  242. it. Your hard disk will contain several versions of NOSE.
  243.   The first version, NOSE.C, is the program you typed. Turbo C 
  244. puts NOSE.C in the TC subdirectory; Quick C puts NOSE.C in the 
  245. BIN subdirectory of the QC2 subdirectory.
  246.   When you say to run, the computer automatically creates and 
  247. runs NOSE.EXE, which is the Executable machine-language version 
  248. of your program. After you quit C, you can run NOSE.EXE by typing 
  249. ``cd \tc'' (for Turbo C) or ``cd \qc2\bin'' (for Quick C) and 
  250. then typing ``nose''.
  251.   You can erase the version called NOSE.OBJ. The computer creates 
  252. it just to help create NOSE.EXE.
  253.   Quick C creates three extra files (NOSE.MDT, NOSE.ILK, and 
  254. NOSE.SYM), which you can erase.
  255.                                                         \n
  256.                                          Here's a short cut. 
  257. Instead of typing ___ 
  258. main(){
  259.         puts("make your nose");
  260.         puts("touch your toes");
  261.         }
  262. you can type:
  263. main(){
  264.         puts("make your nose\ntouch your toes");
  265.         }
  266. The symbol \n means: new line. It tells the computer to press the 
  267. ENTER key. So puts(``make your nose\ntouch your toes'') tells the 
  268. computer to print ``make your nose'', then press the ENTER key, 
  269. then print ``touch your toes''. The computer will print:
  270. make your nose
  271. touch your toes
  272.                                          When you type the symbol 
  273. \n, make sure you type a backslash: \. Do not type a division 
  274. sign: /.
  275.  
  276.                                                       Printf
  277.                                          Instead of saying 
  278. ``puts'', you can say ``printf'', like this:
  279. main(){
  280.         printf("I love her so");
  281.         printf("up in the morning");
  282.         }
  283.                                          The command ``printf'' 
  284. means: perform the print function. That program makes the 
  285. computer print ``I love her so'' and ``up in the morning'' on the 
  286. same line as each other, so the computer will print:
  287. I love her soup in the morning
  288.                                          To force printf to press 
  289. the ENTER key after ``I love her so'', say \n, like this:
  290. main(){
  291.         printf("I love her so\n");
  292.         printf("up in the morning");
  293.         }
  294. That makes the computer print:
  295. I love her so
  296. up in the morning
  297.                                          ``Printf'' differs from 
  298. ``puts'' in two ways:
  299. Printf doesn't make the computer press the ENTER key (unless you 
  300. say \n).
  301.  
  302. Puts handles just strings. Printf is fancier: it can handle 
  303. numbers also. Since printf is fancier, it requires more RAM than 
  304. puts.
  305.  
  306.  
  307.                 MATH
  308.   If you have 750 apples and buy 12 more, how many apples will 
  309. you have altogether? This program prints the answer:
  310. main(){
  311.         printf("you will have %d apples",750+12);
  312.         }
  313.   In the second line, the %d means: a bunch of digits. The 
  314. computer will print ``you will have'', then a bunch of digits, 
  315. then ``apples''. The ``bunch of digits'' will be the answer to 
  316. 750+12. Altogether, the computer will print:
  317. you will have 762 apples
  318.   In C, each printf line begins with a string (such as ``you will 
  319. have %d apples'') and typically ends with a computation (such as 
  320. 750+12). The computer automatically inserts the computation's 
  321. answer into the string.
  322.   If you omit the words ``you will have'' and ``apples'', like 
  323. this ___ 
  324. main(){
  325.         printf("%d",750+12);
  326.         }
  327. the computer will print just the number 762. In that program, if 
  328. you forget the ``%d'' or forget to say printf instead of puts, 
  329. the computer will print wrong answers.
  330.   To print two answers on the same line, say %d twice:
  331. main(){
  332.         printf("%d %d", 21+4, 68+1);
  333.         }
  334. That program makes the computer print both answers:
  335. 25 69
  336. The computer leaves a space between the answers because of the 
  337. space between the %d's. If you omit the space between the %d's 
  338. and say ``%d%d'' instead, the computer will print:
  339. 2569
  340.   Like BASIC and PASCAL, C lets you use the symbols +, -, *, /, 
  341. parentheses, decimal points, and e notation. But if you're not 
  342. careful, the computer will print wrong answers. Here's why. . . . 
  343.  
  344.   Integers versus double precision
  345.   C handles two types of numbers well.
  346.   One type of number is called an integer (or int). An int 
  347. contains no decimal point and no e. For example, -27 and 30000 
  348. are ints.
  349.   The other type of number that C handles well is called a 
  350. double-precision number (or a double). A double contains a 
  351. decimal point or an e. For example, -27.0 and 3e4  are  doubles.  
  352. You can abbreviate:  instead of writing ``-27.0'', you can write 
  353. ``-27.'', and instead of writing ``0.37'' you can write ``.37''.
  354.   To print an int, say ``%d'' in the printf statement. To print a 
  355. double, say ``%.15g'' instead. (The .15 makes the computer print 
  356. 15 significant digits, and the g makes it use a general method of 
  357. printing.)
  358.  
  359.      Largest and tiniest numbers
  360.   The largest permissible int is 32767.    The lowest is -32768.
  361.   If you feed the computer an int that's too large, the computer 
  362. won't complain. Instead, the computer will print a wrong answer!
  363.                                          The largest permissible 
  364. double is approximately 1.7e308. The tiniest is approximately 
  365. 1.7e-308.
  366.  
  367.                                                  Tricky arithmetic
  368.                                          If you combine ints, the 
  369. answer is an int. For example, 2+3 is this int: 5.
  370.                                          11/4 is this int: 2. 
  371. (11/4 is not 2.75.)
  372.                                          If you combine doubles, 
  373. the answer is a double. If you combine an int with a double, the 
  374. answer is a double.
  375.                                          How much is 200*300? 
  376. Theoretically, the answer should be this int: 60000. But since 
  377. 60000 is too large to be an int, the computer will print a wrong 
  378. answer. To make the computer multiply 200 by 300 correctly, ask 
  379. for 200.0*300.0, like this:
  380. main(){
  381.         printf("%.15g",200.0*300.0);
  382.         }
  383. That program makes the computer get the correct answer, 60000.0. 
  384. The computer won't bother printing the ``.0''; it will print:
  385. 60000
  386.  
  387.                                                    Advanced math
  388.                                          The computer can do 
  389. advanced math. For example, it can compute square roots. This 
  390. program makes the computer print the square root of 9:
  391. #include <math.h>
  392. main(){
  393.         printf("%.15g",sqrt(9.0));
  394.         }
  395. The computer will print 3.
  396.                                          Say sqrt(9.0) rather 
  397. than sqrt(9), because the number you find the square root of 
  398. should be double-precision, not an integer. If you make the 
  399. mistake of saying sqrt(9), Turbo C and Quick C will print the 
  400. correct answer but slowly; older versions of C will print a wrong 
  401. answer.
  402.                                          That program's top line 
  403. tells the computer to include a math heading. Begin that line by 
  404. typing the symbol #, and end with the symbol > instead of a 
  405. semicolon or brace. That line makes the computer use a file 
  406. called MATH.H, which is in a subdirectory called INCLUDE, which 
  407. is part of your C subdirectory. That MATH.H file tells the 
  408. computer to make advanced-math answers be double-precision.
  409.                                          If you forget to say 
  410. #include <math.h>, the computer will ignore MATH.H, think 
  411. advanced-math answers are integers, and print wrong answers.
  412.                                          Besides sqrt, you can 
  413. use other advanced math functions. All advanced-math functions 
  414. require that you use double-precision numbers and say #include 
  415. <math.h>. Here's a list of those advanced-math functions.
  416.                                          To handle exponents, you 
  417. can use sqrt (square root), exp (exponential power of e), log 
  418. (logarithm base e), and log10 (logarithm base 10). You can also 
  419. use pow: for example, pow(3.0,2.0) is 3.0 raised to the 2.0 
  420. power.
  421.                                          For trigonometry, you 
  422. can use sin (sine), cos (cosine), tan (tangent), asin (arcsin), 
  423. acos (arccosine), atan (arctangent), sinh (sine hyperbolic), cosh 
  424. (cosine hyperbolic), and tanh (tangent hyperbolic). You can also 
  425. use atan2: for example, atan2(y,x) is the arctangent of y divided 
  426. by x.
  427.                                          For absolute value, use 
  428. fabs (floating absolute). For example, fabs(-2.3) is 2.3.
  429.                                          To round, use floor 
  430. (which rounds down) or ceil (which stands for ``ceiling'' and 
  431. rounds up). For example, floor(26.319) is 26.000, and 
  432. ceil(26.319) is 27.000.
  433.  
  434.           NUMERIC VARIABLES
  435.   Like BASIC, C lets you use variables. For example, you can say:
  436.         n=3;
  437.   A variable's name can be short (such as n) or long (such as 
  438. town_population_in_1988). The name must begin with a letter. The 
  439. name can contain letters, digits, and underlines, but not blank 
  440. spaces. The computer looks at just the first eight characters and 
  441. ignores the rest, so the computer considers 
  442. town_population_in_1988 to be the same as town_pop.
  443.   At the top of your program, say what type of number the 
  444. variable stands for. For example, if n and 
  445. town_population_in_1988 will stand for numbers that are ints and 
  446. mortgage_rate will stand for a double, begin your program by 
  447. saying:
  448. main(){
  449.         int n,town_population_in_1988;
  450.         double mortgage_rate;
  451.   Here's a short cut. Instead of beginning your program by saying 
  452. ___ 
  453. main(){
  454.         int n;
  455.         n=3;
  456. just say:
  457. main(){
  458.         int n=3;
  459.   If you're writing a program in which n starts at 3 and 
  460. population_in_1988 starts at 21000, begin your program by saying:
  461. main(){
  462.         int n=3, population_in_1988=21000;
  463.  
  464.                                               Increasing & decreasing
  465.                                          The symbol ++ means 
  466. ``increase''. For example, ++n means ``increase n''. If you say 
  467. ___ 
  468. main(){
  469.         int n=3;
  470.         ++n;
  471.         printf("%d",n);
  472.         }
  473. the n starts at 3 and increases to 4, so the computer prints 4.
  474.                                          Saying ++n gives the 
  475. same answer as n=n+1, but the computer handles ++n faster.
  476.                                          The symbol ++ increases 
  477. the number by 1, even if the number is a decimal. For example, if 
  478. x is 17.4 and you say ++x, the x will become 18.4.
  479.                                          The opposite of ++ is 
  480. --. The symbol -- means ``decrease''. For example, --n means 
  481. ``decrease n''. Saying --n gives the same answer as n=n-1 but 
  482. faster.
  483.  
  484.                                                 Strange short cuts
  485.                                          If you use the following 
  486. short cuts, your programs will be briefer and run faster.
  487.                                          Instead of saying n=n+2, 
  488. say n+=2, which means ``n's increase is 2''. Similarly, instead 
  489. of saying n=n*3, say n*=3, which means ``n's multiplier is 3''.
  490.                                          Instead of saying ++n 
  491. and then giving another command, say ++n in the middle of the 
  492. other command. For example, instead of saying ___ 
  493.         ++n;
  494.         j=7*n;
  495. say:
  496.         j=7*++n;
  497. That's pronounced: ``j is 7 times an increased n''. So if n was 
  498. 2, saying j=7*++n makes n become 3 and j become 21.
  499.                                          Notice that when you say 
  500. j=7*++n, the computer increases n before computing j. If you say 
  501. j=7*n++ instead, the computer increases n after computing j; so 
  502. j=7*n++ has the same effect as saying:
  503.         j=7*n;
  504.         ++n;
  505.  
  506.                   How to input
  507.   This program predicts how old you'll be ten years from now:
  508. Program                                   Meaning
  509. main(){
  510.         int age;                          The age is an integer.
  511.         printf("How old are you? ");      Ask ``How old are you? 
  512. ''.
  513.         scanf("%d",&age);                 Wait for person to 
  514. input age.
  515.         printf("Ten years from now, you'll be %d years 
  516. old.",age+10);                            Give result.
  517.         }
  518. Notice that in the scanf statement, you must say &age instead of 
  519. age. (If you forget the symbol &, you'll have a runaway pointer 
  520. ___ and a disaster!) Here's a sample run:
  521. How old are you? 27
  522. Ten years from now, you'll be 37 years old.
  523.   The next program converts feet to inches. It even handles 
  524. decimals: it can convert 1.5 feet to 18.0 inches.
  525. Program                           Meaning
  526. main(){
  527.         double feet;              The number of feet is 
  528. double-precision.
  529.         printf("How many feet? ");Ask ``How many feet? ''.
  530.         scanf("%lf",&feet);       Wait for person to input how 
  531. many feet.
  532.         printf("That makes %.15g inches.",feet*12.0);Print the 
  533. result.
  534.         }
  535. Notice that to input a double-precision number, the scanf 
  536. statement must say ``%lf'', which means ``long floating-point'', 
  537. which is a fancy way of saying ``double precision''.
  538.  
  539.                      Arrays
  540.   Like BASIC and PASCAL, C lets you create arrays. For example, 
  541. if you want x to be a list of 3 double-precision numbers, begin 
  542. your program by saying:
  543.         double x[3];
  544. That says x will be a list of 3 double-precision numbers, called 
  545. x[0], x[1], and x[2]. Notice that C starts counting at 0. (PASCAL 
  546. starts counting at 1 instead; PASCAL would call those numbers 
  547. x[1], x[2], and x[3].)
  548.   Here's a complete C program using that array:
  549. main(){
  550.         double x[3];
  551.         x[0]=10.6;
  552.         x[1]=3.2;
  553.         x[2]=1.1;
  554.         printf("%.15g",x[0]+x[1]+x[2]);
  555.         }
  556. The computer will print the sum, 14.9.
  557.   Notice that if you say double x[3], you can refer to x[0], 
  558. x[1], and x[2], but not x[3]. If you accidentally refer to x[3], 
  559. you'll be creating a runaway pointer.
  560.   If you want x to be a table having 2 rows and 3 columns of 
  561. double-precision numbers, begin your program by saying:
  562. main(){
  563.         double x[2][3];
  564. Notice that C says x[2][3]. (PASCAL says x[2,3] instead.) In C, 
  565. if you accidentally say x[2,3] instead of x[2][3], you'll have a 
  566. runaway pointer.
  567.   Since C always starts counting at 0 (not 1), the number in the 
  568. table's upper-left corner is called x[0][0].
  569.  
  570.  
  571.                CHARACTER VARIABLES
  572.   A variable can stand for a character. For example, suppose 
  573. you're in school, take a test, and get an A on it. To proclaim 
  574. your grade, write a program containing this line:
  575.         grade='A';
  576.   Here's the complete program:
  577. Program         Meaning
  578. #include <stdio.h>INCLUDE the STanDard I/O Headers.
  579. main(){
  580.         char grade;The grade is a character.
  581.         grade='A';The grade is `A'.
  582.         putchar(grade);Print the character that's the grade.
  583.         }
  584. The computer will print:
  585. A
  586.   The usual way to print the grade is to say putchar(grade). To 
  587. teach the computer what putchar means, say #include <stdio.h>.
  588.   Another way to print the grade is to say printf(``%c'',grade); 
  589. the ``%c'' means ``character''.
  590.   To input a grade, say scanf(``%c'',&grade) or grade=getchar(). 
  591. If you say scanf(``%c'',&grade), the user must press the ENTER 
  592. key after entering the grade. If you say grade=getchar() instead, 
  593. the user doesn't have to press ENTER. Like putchar, getchar 
  594. requires you to say #include <stdio.h>.
  595.  
  596.               Strings of characters
  597.   A variable can stand for a whole string of characters:
  598. Program                 Meaning
  599. main(){
  600.         char *torture;  Torture is a whole string of characters.
  601.         torture="slice off your head";Here's torture.
  602.         puts(torture);  Print the string that's torture.
  603.         }
  604. The computer will print:
  605. slice off your head
  606.   That program begins by saying char *torture. The * means 
  607. ``string'', so that char * means ``character string''. If you 
  608. omit the *, torture will be just one character instead of a 
  609. string of characters.
  610.   Put each string (such as ``slice off your head'') in 
  611. double-quotes ("). Put a single character (such as `A') in 
  612. single-quotes (').
  613.   To print a string, say puts. To print a single character, say 
  614. putchar.
  615.   The usual way to print the torture string is to say 
  616. puts(torture). Another way is to say printf(``%s'',torture); the 
  617. ``%s'' means ``string''.
  618.   Gets Here's how to input a string:
  619. main(){
  620.         char *name; name=(char *)malloc(41);
  621.         printf("What is your name? ");
  622.         gets(name);
  623.         printf("I like the name %s",name);
  624.         }
  625.   Here's a sample run of that program:
  626. What is your name? Maria Gonzales
  627. I like the name Maria Gonzales
  628.   In that program, the most important line is ``gets(name)''. 
  629. That tells the computer to get a string from the user; it lets 
  630. the user input a name. Notice that to input a string instead of a 
  631. number, you say ``gets'' instead of ``scanf''.
  632.  
  633.   Malloc In that program, the top line says ``name=(char 
  634. *)malloc(41)''. That warns the computer that the person's name 
  635. might consume up to 41 characters in RAM (40 bytes for the name 
  636. itself, plus 1 byte for the end-of-string marker). It makes the 
  637. computer reserve 41 bytes of RAM for the name. The ``malloc'' 
  638. means ``memory allocation''. If you forget to say ``name=(char 
  639. *)malloc(41)'', you'll have a runaway pointer.
  640.   To be extra safe, in case the person types an extra-long name, 
  641. you might be better off saying malloc(51) or even malloc(81). 
  642. Since most strings in most programs are less than 81 characters 
  643. long, here's a rule of thumb: to be safe, say malloc(81) for each 
  644. string.
  645.   In the program that says torture=``slice off your head'', you 
  646. don't have to say torture=(char *)malloc(20), because when the 
  647. computer sees ``slice off your head'' in your program, the 
  648. computer automatically reserves 20 bytes of RAM to hold it. You 
  649. need malloc just for variables that are input or that are built 
  650. up by combining other variables.
  651.   Substrings If torture is ``slice off your head'', torture+1 
  652. means ``torture without the first character''; it is ``lice off 
  653. your head''. Similarly, torture+2 is ``torture without the first 
  654. 2 characters''; it is ``ice off your head''.
  655.   (Technically, torture+2 means ``the string that begins 2 
  656. characters past the beginning of torture''; it's ``the string 
  657. whose starting memory address is 2 higher than torture's''.)
  658.   For example:
  659. Program                 Meaning
  660. main(){
  661.         char *torture;  Torture is a whole string of characters.
  662.         torture="slice off your head";Here's torture.
  663.         printf("%s",torture+2);Print ``ice off your head''.
  664.         }
  665.   Here's how to make cool be torture+2, which is ``ice off your 
  666. head'':
  667. Program                 Meaning
  668. main(){
  669.         char *torture,*cool;Torture and cool are strings.
  670.         torture="slice off your head";Here's torture.
  671.         cool=torture+2; Cool is ``ice off your head''.
  672.         printf("%s",cool);Print ``ice off your head''.
  673.         }
  674. Since cool uses the same part of RAM as torture, cool doesn't 
  675. have to be malloc'ed.
  676.   Extracting a character from a string If torture is ``slice off 
  677. your head'', *torture indicates the first character in torture; 
  678. it is `s'. This program makes the computer print the `s':
  679. Program                 Meaning
  680. #include <stdio.h>      Include the definition of putchar, etc.
  681. main(){
  682.         char *torture,hiss;Torture's a string. Hiss is a 
  683. character.
  684.         torture="slice off your head";Here's torture.
  685.         hiss=*torture;  Hiss is torture's first character, `s'.
  686.         putchar(hiss);  Print `s'.
  687.         }
  688.   If you want to print just torture's third character (which is 
  689. the i), ask for *(torture+2), which means ``the character in 
  690. torture beyond the first 2''; or just ask for torture[2].
  691.   Suppose torture's a string, and you say cool=torture. If you 
  692. change cool's third character to an x (by saying cool[2]=`x'), 
  693. you'll also be changing the third character of torture, since 
  694. cool and torture share characters with each other and share the 
  695. same part of RAM.
  696.  
  697.  
  698.                 LOGIC
  699.   Like most computer languages, C lets you say ``if'', ``while'', 
  700. ``for'', and ``goto'' and create comments and subroutines. Here's 
  701. how. . . . 
  702.  
  703.                  If
  704.   If a person's age is less than 18, let's make the computer say 
  705. ``You are still a minor.'' Here's the fundamental line:
  706.         if (age<18) puts ("You are still a minor.");
  707. Notice you must put parentheses after the word ``if''.
  708.   If a person's age is less than 18, let's make the computer say 
  709. ``You are still a minor.'' and also say ``Ah, the joys of 
  710. youth!'' and ``I wish I could be as young as you!'' Here's how to 
  711. say all that:
  712.         if (age<18){
  713.                 puts("You are still a minor.");
  714.                 puts("Ah, the joys of youth!");
  715.                 puts("I wish I could be as young as you!");
  716.                 }
  717.   Let's put that structure into a complete program:
  718. main(){
  719.         int age;
  720.         printf("how old are you? ");
  721.         scanf("%d",&age);
  722.         if (age<18){
  723.                 puts("You are still a minor.");
  724.                 puts("Ah, the joys of youth!");
  725.                 puts("I wish I could be as young as you!");
  726.                 }
  727.         else{
  728.                 puts("You are an adult.");
  729.                 puts("Now we can have some adult fun!");
  730.                 }
  731.         puts("Glad to have met you.");
  732.         }
  733. If the person's age is less than 18, the computer will print 
  734. ``You are still a minor.'' and ``Ah, the joys of youth!'' and ``I 
  735. wish I could be as young as you!'' If the person's age is not 
  736. less than 18, the computer will print ``You are an adult.'' and 
  737. ``Now we can have some adult fun!'' Regardless of the person's 
  738. age, the computer will end the conversation by saying ``Glad to 
  739. have met you.''
  740.   The ``if'' statement uses this notation:
  741. Notation        Meaning
  742. if (age<18){    if age is less than 18
  743. if (age<=18){   if age is less than or equal to 18
  744. if (age==18){   if age is equal to 18
  745. if (age!=18){   if age is not equal to 18
  746. if (age<18 && weight>200){if age<18 and weight>200
  747. if (age<18 || weight>200){if age<18 or weight>200
  748.   Look at that table carefully! Notice that in the ``if'' 
  749. statement, you must use double symbols: you must say ``=='' 
  750. instead of ``='', say ``&&'' instead of ``&'', and say ``||'' 
  751. instead of ``|''. If you accidentally use single symbols instead 
  752. of double, the computer will print wrong answers.
  753.   Strings To put strings in an ``if'' statement, you must say 
  754. ``strcmp'', which warns the computer to do a ``string 
  755. comparison''.
  756.   For example, suppose x and y are strings, and you want to test 
  757. whether they're equal. Do not say ``if (x==y)''. Instead, say 
  758. ``if (strcmp(x,y)==0)'', which means ``if string comparison 
  759. between x and y shows 0 difference between them''.
  760.                                          To test whether x's 
  761. string comes before y's in the dictionary, do not say ``if 
  762. (x<y)''. Instead, say ``if (strcmp(x,y)<0)''.
  763.  
  764.                                                        While
  765.                                          Let's make the computer 
  766. print the word ``love'' repeatedly, like this:
  767. love love love love love love love love love love love etc. love 
  768. love love love love love love love love love love etc.
  769. love love love love love love love love love love love etc.
  770. etc.
  771. This program does it:
  772. main(){
  773.         while (1) printf("love ");
  774.         }
  775.                                          In that program, the 
  776. ``while (1)'' means: do repeatedly. The computer will do 
  777. printf(``love'') repeatedly, looping forever ___ or until you 
  778. abort the program.
  779.                                          Let's make the computer 
  780. start at 20 and keep counting, so the computer will print:
  781. 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 etc.
  782. This program does it:
  783. Program                                                    
  784. Meaning
  785. main(){
  786.         int i=20;                                          Start 
  787. the integer i at 20.
  788.         while (1){                                         Repeat 
  789. these lines forever:
  790.                 printf("%d ",i);                                   
  791. print i
  792.                 ++i;                                               
  793. increase i
  794.                 }
  795.         }
  796.                                          In that program, if you 
  797. say ``while (i<30)'' instead of ``while (1)'', the computer will 
  798. do the loop only while i remains less than 30; the computer will 
  799. print just:
  800. 20 21 22 23 24 25 26 27 28 29
  801.                                          Instead of saying 
  802. ``while (i<30)'', you can say ``while (i<=29)''.
  803.  
  804.                                                         For
  805.                                          Here's a more natural 
  806. way to get that output of numbers from 20 to 29:
  807. main(){
  808.         int i;
  809.         for (i=20; i<=29; ++i) printf("%d ",i);
  810.         }
  811.                                          In that program, the 
  812. ``for (i=20; i<=29; ++i)'' means ``Do repeatedly. Start with 
  813. i=20, and keep repeating as long as i<=29. At the end of each 
  814. repetition, do ++i.''
  815.                                          In that ``for'' 
  816. statement, if you change the ++i to i+=3, the computer will 
  817. increase i by 3 instead of by 1, so that the computer will print:
  818. 20 23 26 29
  819.                                          The ``for'' statement is 
  820. quite flexible. You can even say ``for (i=20; i<100; i*=2)'', 
  821. which makes i start at 20 and keep doubling, so the computer 
  822. prints:
  823. 20 40 80
  824.                                          Like ``if'' and 
  825. ``while'', the ``for'' statement can sit atop a group of indented 
  826. lines that are in braces.
  827.                 Goto
  828.   You can say ``goto''. For example, if you say ``goto yummy'', 
  829. the computer will go to the line whose name is yummy:
  830. main(){
  831.         puts("my dog");
  832.         goto yummy;
  833.         puts("never");
  834.         yummy: puts("drinks whiskey");
  835.         }
  836.   The computer will print:
  837. my dog
  838. drinks whiskey
  839.  
  840.               Comments
  841.   To put a comment in your program, begin the comment with the 
  842. symbol /* and end it with */. Here's an example:
  843. /* The following program
  844. is fishy */
  845. main(){
  846.         puts("Our funny God"); /* notice religious motif */
  847.         puts("invented cod");  /* said by nasty flounder */
  848.         }
  849. The computer will print just:
  850. Our funny God
  851. invented cod
  852.  
  853.              Subroutines
  854.   Like PASCAL, C lets you invent subroutines and give them names. 
  855. For example, here's how to invent a subroutine called ``insult'' 
  856. and use it in the main routine:
  857. Program               Meaning
  858. main(){               Here's main routine:
  859.         puts("We all know...");print ``We all know...''
  860.         insult();     do the insult
  861.         puts("...but we love you");print the ending
  862.         }
  863. insult(){             How to insult:
  864.         puts("you are stupid");print ``you are stupid''
  865.         puts("you are ugly");print ``you are ugly''
  866.         }
  867. The computer will print:
  868. We all know...
  869. you are stupid
  870. you are ugly
  871. ...but we love you
  872.   Like BASIC, C wants you to type the main routine first, then 
  873. the definition of the subroutine (called ``insult'').
  874.   Whenever you write a subroutine's name, you must put 
  875. parentheses afterwards, like this: insult(). Those parentheses 
  876. tell the computer: insult's a subroutine, not a variable.
  877.   Here's another example:
  878. Program                 Meaning
  879. main(){                 The main routine says
  880.         laugh();        to laugh.
  881.         }
  882. laugh(){                Here's how to laugh:
  883.         int i;          print ``ha'' 100 times.
  884.         for (i=1; i<=100; ++i) printf("ha ");
  885.         }
  886. The main routine says to laugh. The subroutine defines ``laugh'' 
  887. to mean: print ``ha '' a hundred times. Notice that the ``int i'' 
  888. is in the subroutine, not the main routine.
  889.                                          Let's create a more 
  890. flexible subroutine, so that whenever the main routine says 
  891. laugh(2), the computer will print ``ha ha''; whenever the main 
  892. routine says laugh(5), the computer will print ``ha ha ha ha 
  893. ha''; and so on. Here's how:
  894. main(){
  895.         puts("Here is a short laugh");
  896.         laugh(2);
  897.         puts("\nHere is a longer laugh");
  898.         laugh(5);
  899.         }
  900. laugh(int n){                                                  
  901. Here's how to laugh(n):
  902.         int i;                                                 
  903. print ``ha'', n times.
  904.         for (i=1; i<=n; ++i) printf("ha ");
  905.         }
  906.                                          Average Let's define the 
  907. ``average'' of a pair of integers, so that ``average(3,7)'' means 
  908. the average of 3 and 7 (which is 5), and so a main routine saying 
  909. ``i=average(3,7)'' makes i be 5.
  910.                                          This subroutine defines 
  911. the ``average'' of all pairs of integers:
  912. average(int a, int b){
  913.         return ((a+b)/2);
  914.         }
  915. The top line says, ``Here's how to find the average of any two 
  916. integers, a and b.'' The next line says, ``Return to the main 
  917. routine, with this answer: (a+b)/2.''
  918.                                          Notice that the word 
  919. ``return'' must be followed by parentheses.
  920.                                          Double-precision average 
  921. Let's revise the subroutine, to make it handle double-precision 
  922. numbers instead of integers, so a main routine saying 
  923. ``x=average(3.0,7.0)'' makes x be 5.0.
  924.                                          Here's how:
  925. double average(double a, double b){
  926.         return ((a+b)/2.0);
  927.         }
  928. The subroutine begins by saying ``double average''. That says the 
  929. average will be a double-precision number. If you omit the word 
  930. ``double'' and say just ``average'', the computer will make the 
  931. average be an integer instead, because the computer assumes all 
  932. subroutine answers are integers, unless you specifically say 
  933. ``double'' or ``char'' or some other alternative.
  934.                                          So to get a 
  935. double-precision answer, you must begin the subroutine by saying 
  936. ``double''. You must also say ``double'' in the main routine:
  937. main(){
  938.         double x,average();
  939.         x=average(3.0,7.0);
  940.         printf("%.15g",x);
  941.         }
  942.